<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import {
  ElButton,
  ElMessage,
  ElSelect,
  ElOption,
  ElForm,
  ElFormItem,
  ElCol,
  ElRow,
  ElInput
} from 'element-plus'
import { Table } from '@/components/Table'
import {
  consigneeIndex,
  consigneeAdd,
  consigneeEdit,
  placeendSelect,
  submarketSelect,
  consigneeDEL,
  consigneeSelect,
  empSelect,
  clientSelect
} from '@/api/common'
import { useTable } from '@/hooks/web/useTable'
import { placestartType } from '@/api/common/types'
import { ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
// import { TableColumn } from '@/types/table'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useCache } from '@/hooks/web/useCache'
const appStore = useAppStoreWithOut()
const { wsCache } = useCache()
//用户权限数组
const userRlues = wsCache.get(appStore.getUserInfo).rlues
const userId = wsCache.get(appStore.getUserInfo).id
const checkRlues = (rlues) => {
  //检查权限
  if (userRlues.includes(rlues)) {
    return true
  } else {
    ElMessage.error('当前用户无权限操作，请联系管理员')
    return false
  }
}

//目的地
// const destinationArr: any = reactive([])
// const getplaceendSelect = async () => {
//   let res: any = await placeendSelect()
//   res.data.list.forEach((item) => {
//     destinationArr.push({
//       label: item.name,
//       value: item.id
//     })
//   })
// }
// getplaceendSelect()

//分货市场
// const submarketArr: any = reactive([])
// const getsubmarketSelect = async () => {
//   let res: any = await submarketSelect()
//   res.data.list.forEach((item) => {
//     submarketArr.push({
//       label: item.name,
//       value: item.id
//     })
//   })
// }
// getsubmarketSelect()
const { register, tableObject, methods } = useTable<placestartType>({
  getListApi: consigneeIndex,
  delListApi: consigneeDEL,
  response: {
    list: 'data',
    total: 'total'
  },
  defaultParams: {
    title: ''
  },
  find: ''
})
const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'client_code',
    label: t('customerManagement.customerNo'),
    type: 'string',
    form: {
      show: true,
      component: 'Select',
      componentProps: {
        filterable: true
      },
      api: async () => {
        const res = await clientSelect()
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.code
          })
        })
        return list
      }
    },
    detail: {
      show: false
    }
  },
  {
    field: 'salesman',
    label: t('personnelManagementemp.salesman'),
    type: 'string',
    form: {
      show: true,
      component: 'Select',
      api: async () => {
        const res = await empSelect()
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        return list
      }
    },
    detail: {
      show: false
    }
  },
  {
    field: 'placeend',
    label: t('router.destination'),
    type: 'string',
    table: {
      show: false
    },
    form: {
      show: true,
      component: 'Select',
      componentProps: {
        filterable: true
      },
      api: async () => {
        const res = await placeendSelect()
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        return list
      }
    },
    detail: {
      show: false
    }
  },
  {
    field: 'placeend.name',
    label: t('router.destination'),
    type: 'string',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'submarket',
    label: t('router.distributionMarket'),
    type: 'string',
    table: {
      show: false
    },
    form: {
      show: true,
      component: 'Select',
      api: async () => {
        const res = await submarketSelect()
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        return list
      }
    },
    detail: {
      show: false
    }
  },
  {
    field: 'submarket.name',
    label: t('router.distributionMarket'),
    type: 'string',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'name',
    label: '收货人',
    search: {
      show: true
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'email',
    label: t('descriptionsDemo.email'),
    search: {
      show: true
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'mobile',
    label: t('CustomsClearanceFormCompany.phone'),
    search: {
      show: true
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  tableObject.currentRow = null
  dialogVisible.value = true
  actionType.value = ''
}

const delLoading = ref(false)

const delData = async (row: placestartType | null, multiple: boolean, rlus: string) => {
  if (!checkRlues(rlus)) return false

  tableObject.currentRow = row
  const { delList, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delList(
    multiple ? selections.map((v) => v.id) : [tableObject.currentRow?.id as string],
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}

const actionType = ref('')

const action = (row: placestartType, type: string, rlus: string) => {
  if (!checkRlues(rlus)) return false

  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  tableObject.currentRow = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const addSave = async () => {
  const write = unref(writeRef)
  await write?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data: any = (await write?.getFormData()) as placestartType
      let obj: any = {
        client_code: data.client_code,
        email: data.email,
        mobile: data.mobile,
        name: data.name,
        placeend_id: data.placeend,
        salesman: data.salesman,
        submarket_id: data.submarket
      }
      const res = await consigneeAdd(obj)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        getList()
      }
    }
  })
}
const save = async () => {
  const write = unref(writeRef)
  await write?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await write?.getFormData()) as placestartType
      const res = await consigneeEdit(data, data.id)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        getList()
      }
    }
  })
}
</script>

<template>
  <ContentWrap>
    <Search
      :model="{}"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <ElButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData(null, true)">
        {{ t('exampleDemo.del') }}
      </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.limit"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton type="primary" @click="action(row, 'edit', '4-2')">
          {{ t('exampleDemo.edit') }}
        </ElButton>
        <ElButton type="danger" @click="delData(row, false, '4-3')">
          {{ t('exampleDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton
        v-if="actionType !== 'detail' && actionType !== 'edit'"
        type="primary"
        :loading="loading"
        @click="addSave"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton v-if="actionType == 'edit'" type="primary" :loading="loading" @click="save">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
